<template>
  <a-form
      layout="inline"
      :model="formState"
      @finish="handleFinish"
      @finishFailed="handleFinishFailed"
  >
    <a-form-item>
      <a-input v-model:value="formState.user" placeholder="Username">
        <template #prefix>
          <UserOutlined style="color: rgba(0, 0, 0, 0.25)"/>
        </template>
      </a-input>
    </a-form-item>
    <a-form-item>
      <a-input v-model:value="formState.password" type="password" placeholder="Password">
        <template #prefix>
          <LockOutlined style="color: rgba(0, 0, 0, 0.25)"/>
        </template>
      </a-input>
    </a-form-item>
    <a-form-item>
      <a-button
          type="primary"
          html-type="submit"
          :disabled="formState.user === '' || formState.password === ''"
      >
        登 录
      </a-button>
    </a-form-item>
  </a-form>
</template>
<script>
// import {createNamespacedHelpers, mapActions} from "vuex"
import {UserOutlined, LockOutlined} from '@ant-design/icons-vue';
import {defineComponent, reactive} from 'vue';
import {useStore} from "vuex"
import {getUserInfo, login} from '@/api/user'
import {message} from "ant-design-vue";
import {get_user_list} from "@/utils/request_user";
import {useRouter} from "vue-router"

export default defineComponent({


  setup() {
    const router = useRouter()
    //vuex
    const store = useStore() // 获取store 实例
    const formState = reactive({
      user: '',
      password: '',
    });

    async function get_user_info() {
      const res = await getUserInfo()
      if (res.code === 1) {
        store.commit("SET_USER_DATA", res.data)
        return
      }
      message.warning("获取用户信息失败")
    }

    const handleFinish = async (values) => {
      let params = {
        "userName": formState.user,
        "password": formState.password
      }
      const res = await login(params)
      if (res.code === 1) {
        store.commit("SET_TOKEN", res.data.token)
        sessionStorage.setItem('token', res.data.token)
        message.success('用户登录成功');
        await router.replace("/index/system/user")
        // await router.replace("/index")
        await get_user_list()
        await get_user_info()
        return
      }
      message.error("用户登录异常，请检查账号密码")

    };

    const handleFinishFailed = errors => {
      console.log(errors);
    };

    return {
      formState,
      handleFinish,
      handleFinishFailed,
    };
  },
  // data() {
  //   return {
  //     formState: {
  //       user: 'longbin',
  //       password: '123456',
  //     }
  //   }
  // },
  // methods: {
  //   ...mapActions(['Login']),
  //
  // },

  components: {
    UserOutlined,
    LockOutlined,
  },
});
</script>
